//package com.pig4cloud.pigx.user.schedule;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.util.NumberUtil;
//import cn.hutool.core.util.StrUtil;
//import cn.hutool.json.JSONUtil;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.google.protobuf.ByteString;
//import com.pig4cloud.pigx.common.customize.enums.CommonDictEnum;
//import com.pig4cloud.pigx.common.customize.utils.id.IdWorker;
//import com.pig4cloud.pigx.common.data.resolver.ParamResolver;
//import com.pig4cloud.pigx.user.constant.WalletConstant;
//import com.pig4cloud.pigx.user.dto.TronContractsEventsTransfer;
//import com.pig4cloud.pigx.user.entity.Currency;
//import com.pig4cloud.pigx.user.entity.CurrentBlock;
//import com.pig4cloud.pigx.user.entity.RechargeRecord;
//import com.pig4cloud.pigx.user.entity.UserAddress;
//import com.pig4cloud.pigx.user.enums.RechargeRecordEnum;
//import com.pig4cloud.pigx.user.enums.UserEnums;
//import com.pig4cloud.pigx.user.service.CurrencyService;
//import com.pig4cloud.pigx.user.service.CurrentBlockService;
//import com.pig4cloud.pigx.user.service.RechargeRecordService;
//import com.pig4cloud.pigx.user.service.UserAddressService;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.Response;
//import org.springframework.scheduling.annotation.EnableScheduling;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//import org.tron.trident.core.ApiWrapper;
//import org.tron.trident.utils.Base58Check;
//
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.time.LocalDateTime;
//import java.util.List;
//import java.util.concurrent.TimeUnit;
//import java.util.stream.Collectors;
//
///**
// * tron 充值
// *
// */
//@Slf4j
//@Component
//@EnableScheduling
//@AllArgsConstructor
//public class TronRecharge {
//	private final OkHttpClient okHttpClient;
//
//	private final CurrentBlockService currentBlockService;
//
//	private final CurrencyService currencyService;
//
//	private final UserAddressService addressService;
//
//	private final RechargeRecordService rechargeRecordService;
//
//	private final IdWorker idWorker;
//
//	@Scheduled(fixedDelay = 1000)
//	public void task() {
//		try {
//			// 获取当前区块
//			CurrentBlock currentBlock = currentBlockService.getOne(new LambdaQueryWrapper<CurrentBlock>()
//					.eq(CurrentBlock::getPublicChain, UserEnums.Chain.TRON.getValue())
//			);
//			// 币种
//			Currency currency = currencyService.getOne(new LambdaQueryWrapper<Currency>()
//					// 公链
//					.eq(Currency::getPublicChain, UserEnums.Chain.TRON.getValue())
//					.eq(Currency::getName, WalletConstant.USDT)
//					.eq(Currency::getState, CommonDictEnum.Status.NORMAL.getValue())
//			);
//			if (currentBlock == null) {
//
//				currentBlock = new CurrentBlock();
//				currentBlock.setPublicChain(UserEnums.Chain.TRON.getValue());
//				currentBlock.setBlockNumber(String.valueOf(this.getLastBlockNumber(currency)));
//				currentBlockService.save(currentBlock);
//			}
//
//			String blockNumber = currentBlock.getBlockNumber();
//			CurrentBlock currentBlockUpdate = new CurrentBlock();
//			currentBlockUpdate.setId(currentBlock.getId());
//			do {
//				try {
//					if (this.getLastBlockNumber(currency).compareTo(new BigDecimal(blockNumber)) <= 0) {
//						TimeUnit.MILLISECONDS.sleep(ParamResolver.getLong("TRON_BLOCK_READ_TIME_INTERVAL"));
//						continue;
//					}
//					okhttp3.Request request = new Request.Builder()
//							.url(currency.getNodeAddress() + "v1/contracts/" +
//									currency.getSmartContractAddress() + "/events?event_name=Transfer&block_number=" +
//									blockNumber + "&only_confirmed=true&limit=200")
//							.get()
//							.addHeader("accept", "application/json")
//							.build();
//					this.tronNext(request,currency);
//					BigDecimal add = NumberUtil.add(blockNumber, "1");
//					blockNumber = String.valueOf(add);
//					currentBlockUpdate.setBlockNumber(String.valueOf(add));
//					currentBlockService.updateById(currentBlockUpdate);
//
//				} catch (InterruptedException e) {
//					throw new RuntimeException(e);
//				}
//			} while (true);
//		} catch (Exception e) {
//			log.error("btron充值定时任务 inTime[" + LocalDateTime.now() + "] error + " + e);
//		}
//		log.error("tron充值定时任务 inTime[" + LocalDateTime.now() + "] success");
//	}
//
//	public void tronNext(okhttp3.Request request,Currency currency) {
//		Response response = null;
//		try {
//			response = okHttpClient.newCall(request).execute();
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//		String res = null;
//		try {
//			res = response.body().string();
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//		TronContractsEventsTransfer tronContractsEventsTransfer = JSONUtil.toBean(res, TronContractsEventsTransfer.class);
//		if (tronContractsEventsTransfer.getData() == null) {
//			return;
//		}
//		tronContractsEventsTransfer.getData().forEach(o -> {
//			// 用户列表
//			List<UserAddress> accountList = addressService.list(new LambdaQueryWrapper<UserAddress>()
//					.eq(UserAddress::getChain, UserEnums.Chain.TRON.getValue())
//			);
//			if (CollUtil.isNotEmpty(accountList)) {
//				// 获取所有用户地址
//				List<String> addressList = accountList.stream().map(UserAddress::getAddress).collect(Collectors.toList());
//				String toRes = o.getResult().getTo();
//				String replace = StrUtil.replace(toRes, 0, 2, "41");
//				ByteString bytes = ApiWrapper.parseAddress(replace);
//				String tronAddress = Base58Check.bytesToBase58(bytes.toByteArray());
//
//				if (CollUtil.contains(addressList, tronAddress)) {
//					log.info("tron地址匹配成功,交易哈希：{}", o.getTransactionId());
//
//					RechargeRecord recordServiceOne = rechargeRecordService.getOne(new LambdaQueryWrapper<RechargeRecord>()
//							.eq(RechargeRecord::getTransactionHash, o.getTransactionId())
//					);
//
//					if (recordServiceOne != null) {
//						log.error("tron存在相同交易哈希：{}", o.getTransactionId());
//						return;
//					}
//					UserAddress userAddress = accountList.stream().filter(account -> StrUtil.equals(account.getAddress(), tronAddress)).findFirst().get();
//					// 充值记录
//					RechargeRecord rechargeRecord = new RechargeRecord();
//					rechargeRecord.setId(idWorker.nextId());
//					// 公链
//					rechargeRecord.setPublicChain(UserEnums.Chain.TRON.getValue());
//					// 账户地址id
//					rechargeRecord.setAddressId(userAddress.getId());
//					// 用户id
//					rechargeRecord.setUserId(userAddress.getUserId());
//					// 区块
//					rechargeRecord.setBlockNumber(String.valueOf(o.getBlockNumber()));
//					// 充值数量
//					BigDecimal bigDecimal = NumberUtil.toBigDecimal(o.getResult().getValue()).movePointLeft(6);
//					rechargeRecord.setQuantity(bigDecimal);
//					// 到账地址
//					rechargeRecord.setArrivalAddress(tronAddress);
//					// 来源地址
//					String fromRes = o.getResult().getFrom();
//					String fromRep = StrUtil.replace(fromRes, 0, 2, "41");
//					ByteString fromBytes = ApiWrapper.parseAddress(fromRep);
//					String fromAddress = Base58Check.bytesToBase58(fromBytes.toByteArray());
//					rechargeRecord.setSourceAddress(fromAddress);
//					// 区块确认数
//					rechargeRecord.setBlockConfirmationNumber("0");
//					// 交易哈希
//					rechargeRecord.setTransactionHash(o.getTransactionId());
//					// 充值区块确认数
//					rechargeRecord.setBlockConfirmationRechargeNumber(currency.getConfirmationBlockRechargeNumber());
//					// 最小充值数
//					rechargeRecord.setMinimumRechargeNumber(currency.getMinimumRechargeAmount());
//					// 手续费
//					rechargeRecord.setServiceCharge(currency.getServiceCharge());
//					// 币种
//					rechargeRecord.setCurrency(currency.getName());
//					// 状态
//					rechargeRecord.setState(RechargeRecordEnum.Status.RECHARGING.getValue());
//					// 充值类型
//					rechargeRecord.setType(RechargeRecordEnum.Type.CHAIN_RECHARGE.getValue());
//					rechargeRecordService.save(rechargeRecord);
//
//				}
//			}
//
//		});
//
//
//	}
//
//	/**
//	 * 获取波场区块
//	 * @param currency
//	 * @return
//	 */
//	public BigDecimal getLastBlockNumber(Currency currency) {
//		// 查询最新block
//		okhttp3.Request request = new okhttp3.Request.Builder()
//				.url(currency.getNodeAddress() + "walletsolidity/getnowblock")
//				.get()
//				.addHeader("Accept", "application/json")
//				.build();
//
//		Response response = null;
//		try {
//			response = okHttpClient.newCall(request).execute();
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//		String res = null;
//		try {
//			res = response.body().string();
//			String blockNumber = JSONUtil.parseObj(res).getJSONObject("block_header").getJSONObject("raw_data").getStr("number");
//			return new BigDecimal(blockNumber);
//		} catch (Exception e) {
//			throw new RuntimeException(e);
//		}
//	}
//
//}
